package com.xiaoqi.controller;

import com.xiaoqi.constant.MessageConstant;
import com.xiaoqi.constant.RedisMessageConstant;
import com.xiaoqi.pojo.Result;
import com.xiaoqi.utils.SMSUtils;
import com.xiaoqi.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author PC
 * creationTime: 2022/11/18 19:42
 */
@RequestMapping("/validateCode")
@RestController
public class ValidateCodeController {


    @Autowired
    private JedisPool jedisPool;
    /**
     * 发送短信验证码
     * @return
     */
    @PostMapping("/send4Order")
    public Result send4Order(String telephone){

        Jedis jedis = jedisPool.getResource();

        //拼接key
        String key = RedisMessageConstant.SENDTYPE_ORDER+"_"+telephone;
        // 先通过用户传的手机号码查询redis是否有这个key
        String isinrediskey = jedis.get(key);
        if (null==isinrediskey){
            //使用验证码生成工具类生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //发送验证码
            SMSUtils.sendSingleMessageForCode(telephone,new String[]{code+""});
            //在将发送的验证码往redis存一份，并设置有效时间
            jedis.setex(key,5*60,code+"");

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }
        return new Result(false, MessageConstant.SENT_VALIDATECODE);
    }

    @PostMapping("/send4Login")
    public Result send4Login(String telephone){

        Jedis jedis = jedisPool.getResource();
        //拼接key
        String key = RedisMessageConstant.SENDTYPE_LOGIN+"_"+telephone;
        // 先通过用户传的手机号码查询redis是否有这个key
        String isinrediskey = jedis.get(key);
        if (null==isinrediskey){
            //使用验证码生成工具类生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //发送验证码
            SMSUtils.sendSingleMessageForCode(telephone,new String[]{code+""});
            //在将发送的验证码往redis存一份，并设置有效时间
            jedis.setex(key,5*60,code+"");

            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }
        return new Result(false, MessageConstant.SENT_VALIDATECODE);
    }

}
